package mclight.selectors;
import flash.display.DisplayObjectContainer;
import flash.display.Sprite;
import flash.events.Event;
import mclight.Component;
import mclight.containers.Container;
import mclight.text.InputText;

class ColorChooser extends Component
{
	public function new(
		?parent:DisplayObjectContainer, ?container:Container, xpos:Float = 0, ypos:Float = 0,
		value:UInt = 0xff0000, defaultHandler:Event->Dynamic = null
	)
	{
		_value = 0xff0000;
		_value = value;
		super(parent, container, xpos, ypos);
		if(defaultHandler != null)
		{
			//addEventListener(Event.CHANGE, defaultHandler);
		}
	}
	
	override function init():Void
	{
		super.init();
		_width = 65;
		_height = 15;
		value = _value;
	}
	
	var _input:InputText;
	
	var _swatch:Sprite;
	
	override function construct():Void
	{
		_input = new InputText();
		_input.width = 60;
		_input.restrict = "0123456789ABCDEFabcdef";
		_input.maxChars = 6;
		_input.addTo(_sprite);
		//_input.addEventListener(Event.CHANGE, onChange);
		
		_swatch = new Sprite();
		_swatch.x = 62;
		_swatch.filters = [getComponentShadow(2, true)];
		_sprite.addChild(_swatch);
	}
	
	// PUBLIC METHODS
	
	public override function draw():Void
	{
		super.draw();
		_swatch.graphics.clear();
		_swatch.graphics.beginFill(_value);
		_swatch.graphics.drawRect(0, 0, 18, 18);
		_swatch.graphics.endFill();
	}
	
	// HANDLERS
	
	function onChange(event:Event):Void
	{
		event.stopImmediatePropagation();
		_value = Std.parseInt('0x' + _input.text);
		_input.text = _input.text.toUpperCase();
		invalidate();
		//dispatchEvent(new Event(Event.CHANGE));
	}
	
	// PROPERTIES
	
	public var value(getValue, setValue):UInt;
	var _value:UInt;
	function setValue(value:UInt):UInt
	{
		_value = value;
		_input.text = StringTools.hex(value);
		invalidate();
		return value;
	}
	function getValue():UInt
	{
		return _value;
	}
}
